
class Print implements Runnable{
    //定义字符串s1、s2 - 用于通过线程的名字判断当前运行的线程
    String s1 = "PrintNum";
    String s2 = "PrintWord";
    //打印内容
    int[] number = new int[]{1,2,3,4,5,6,7,8,9,10,11,12};
    String[] Word = new String[]{"OneJanuary","TwoFebruary","ThreeMarch",
            "FourApril","FiveMay","SixJune","SevenJuly","EightAugust",
            "NineSeptember","TenOctober","ElevenNovember","TwelveDecember"};

    @Override
    public synchronized void run() {
        if(Thread.currentThread().getName().equals(s1)){//当前线程为number时
            try {
                for (int n:number) {//打印数字
                    System.out.print(n);
                    notify();//通知线程word结束等待
                    wait();//当前线程进入等待状态
                }
            }
            //当word线程调用notify()方法通知number结束等待时时，抓住number抛出的异常，线程重新排队等待CPU资源
            catch (InterruptedException e){}
        }else if (Thread.currentThread().getName().equals(s2)){//当前线程为word时
            try {
                for (String s:Word) {//打印单词
                    System.out.print(s);
                    notify();//通知线程number结束等待
                    wait();//当前线程进入等待状态
                }
            }
            //当number线程调用notify()方法通知word结束等待时时，抓住word抛出的异常，线程重新排队等待CPU资源
            catch (InterruptedException e){}
        }
        notify();//用于通知最后一个执行的线程结束等待，执行完毕使程序结束
    }
}

public class TestDemo {
    public static void main(String[] args) {
        Print print = new Print();//创建任务对象

        Thread number = new Thread(print);//创建线程number - 打印数组
        Thread word = new Thread(print);//创建线程word - 打印单词
        number.setPriority(10);//设置number的优先级为10 -> 每次优先打印数字

        number.setName(print.s1);//设置number线程的名字
        word.setName(print.s2);//设置word线程的名字

        number.start();//启动number线程
        word.start();//启动word线程
    }
}
